<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAdminImpersonationLogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('admin_impersonation_logs', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('admin_user_id'); // A端用户ID
            $table->unsignedBigInteger('tenant_id'); // 被切换的租户ID
            $table->unsignedBigInteger('tenant_user_id')->nullable(); // 被切换的租户用户ID
            $table->datetime('started_at'); // 切换开始时间
            $table->datetime('ended_at')->nullable(); // 切换结束时间
            $table->string('ip_address'); // IP地址
            $table->text('reason')->nullable(); // 切换原因
            $table->enum('status', ['active', 'ended'])->default('active'); // 状态
            $table->timestamps();
            
            // 外键和索引
            $table->foreign('admin_user_id')->references('id')->on('admin_users')->onDelete('cascade');
            $table->foreign('tenant_id')->references('id')->on('tenants')->onDelete('cascade');
            $table->index(['admin_user_id', 'started_at']);
            $table->index(['tenant_id', 'status']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('admin_impersonation_logs');
    }
}